<?php

class Core_Controller_Admincp_Mail_Add extends Nuo_Controller_Admincp
{
	function execute($request)
	{
		Nuo::setVar('breadcrum', array(
			//'title' => 'Edit Template',
			'toolbar' => 'admicp/mail/template',
			'links' => array(
				'admincp' => 'AdminCP',
				'admincp/core/mail' => 'Mails',
				'admincp/core/mail' => 'Templates',
			)
		));

		$table = Nuo::getTable('core/mail');

		$form = Nuo::getObject('core/form/admincp/mail/add');

		$lang = $request->getParam('lang_id');
		
		if(!$lang)
		{
			$lang  =  Intl::getLanguage();
		}
		
		$templateId = $request -> getParam('template_id');

		$item = NULL;

		if ($templateId)
		{
			$item = $table -> find($templateId) -> current();
		}

		if ($request -> isGet() && $item)
		{

			$form -> setData($item -> toArray());
			
			$form->getChild('lang_id')->setValue($lang);

			$translation = $item -> getTranslation($lang, TRUE);

			if ($translation)
			{
				$form -> getChild('subject') -> setValue($translation -> subject);
				$form -> getChild('body_html') -> setValue($translation -> body_html);
				$form -> getChild('body_text') -> setValue($translation -> body_text);
			}
		}

		if ($request -> isPost() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			if (!$item)
			{
				$item = $table -> fetchNew();
			}

			$item -> fromArray($data);
			
			$item -> updated_at = time();

			$item -> save();
			
			$translation = $item -> getTranslation($lang, FALSE);

			if (!$translation)
			{
				$translation = Nuo::getTable('core/mail/translation')->fetchNew();
				$translation->template_id  =  $item->getId();
				$translation->lang_id  =  $lang;
			}
			
			$translation->subject =  $data['subject'];
			$translation->body_html =  $data['body_html'];
			$translation->body_text =  $data['body_text'];
			$translation->save();

			Nuo_Messenger::instance()->add('Template is updated!');
			
			$uri  = Nuo::getUrl('admincp/mail');
			
			Nuo::redirect($uri);
		}

		return  $this -> render(array('form' => $form));
	}

}
